package Socket.test.server_socket;

import Socket.test.DBUtils.User;
import com.sun.corba.se.impl.activation.ServerTableEntry;
import org.dom4j.io.XMLWriter;
import org.junit.Test;
import org.omg.Dynamic.Parameter;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.Executors;

public class Server {

    public static void main(String[] args) throws Exception {

        //创建ServerSocket对象
        final ServerSocket serverSocket = new ServerSocket(22222);
        while (true) {
            //服务器监听客户端的连接请求(阻塞),如果有客户端连接,则返回一个客户端的Socket对象
            final Socket socket = serverSocket.accept();
            Executors.newCachedThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("有客户端连接了:" + socket.getInetAddress().getHostAddress());
                        byte[] buf = new byte[1024];
                        int len = socket.getInputStream().read(buf);
                        System.out.println("服务器收到了数据:");
                        String str = new String(buf, 0, len);                 //获得是整个Get请求体

                        //String url = "http:127.0.0.1:22222/user?method=login&username=admin&password=admin123";

                        //从Get请求体中分离出url地址栏
                        int http = str.indexOf("HTTP");
                        int i = str.indexOf("/");
                        String substr = str.substring(i,http-1);   //   /user?method=login&username=admin&password=admin123


                        int indexof = substr.indexOf("?");
                        String pattern = substr.substring(0,indexof);             //  /url
                        String parameters = substr.substring(indexof+1);          //参数

                        System.out.println(pattern);

                        String[]  parameter = parameters.split("&");
                        HashMap<String,String> map = new HashMap<>(); //内部维持一个Map集合，用于保存URl中的数据

                        for (String pars: parameter){
                            String[] splits = pars.split("=");
                            for(int j=0;j<splits.length;j+=2){
                                map.put(splits[j],splits[j+1]);
                            }

                        }

                        System.out.println(map.get("method"));
                        System.out.println(map.get("username"));
                        System.out.println(map.get("password"));

                        //解析config.xml文件，得到 servlet-class
                        String className = XmlUtils.getClassName(pattern);
                        //通过反射来直接具体的方法
                        Class clazz = Class.forName(className);
                        Method method = clazz.getMethod(map.get("method"), String.class, String.class);
                        String result = (String)method.invoke(clazz.getInterfaces(),map.get("username") , map.get("password"));

                        socket.getOutputStream().write(result.getBytes());

                    } catch (IOException e) {
                        e.printStackTrace();
                    }  catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });


        }
            //String xpth = "//servlet[servlet-name=//servlet-mapping[url-pattern="+url+"]/servlet-name/text()]/servlet-class";
    }
}
//        InputStream inputStream = accept.getInputStream();
//
//        System.out.println( inputStream.read());
//
//        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));


//
//        StringBuffer acceptstr =new StringBuffer();
//        String info = null;
//        while((info= reader.readLine())!=null){
//           if(info!=null){
//               acceptstr.append(info);
//           }
//
//        }
//         accept.shutdownInput();
//
//
//        String strs = "http:127.0.0.1:22222/booEstore/user?method=login&username=admin&password=admin123";
//        int lastIndexOf = strs.lastIndexOf("/");
//        String substring = strs.substring(lastIndexOf );
//        int indexof = substring.indexOf("?");
//        String pattern = substring.substring(0,indexof);             //url-pattern
//        String parameters = substring.substring(indexof+1);          //参数
//
//        String[]  parameter = parameters.split("&");
//        HashMap<String,String> map = new HashMap<String,String>(); //内部维持一个Map集合，用于保存URl中的数据
//
//        for (String str: parameter){
//           String[] splits = str.split("=");
//            for(int i=0;i<splits.length;i+=2){
//                map.put(splits[i],splits[i+1]);
//            }
//
//       }
//
//        System.out.println(map.get("method"));
//        System.out.println(map.get("username"));
//        System.out.println(map.get("password"));
//
//        //读取xml文件，获取到具体的类的全名
//        String className = XmlUtils.getClassName(pattern);
//
//        //通过反射来直接具体的方法
//        Class clazz = Class.forName(className);
//        Object object = clazz.newInstance();
//        Method method = clazz.getMethod(map.get("method"), String.class, String.class);
//        User user = (User)method.invoke(clazz.getInterfaces(),map.get("username") , map.get("password"));
//
//        System.out.println("用户名："+ user.getUsername());
//        System.out.println("密  码："+ user.getPassword());
//    }
//
//
//    String url = "/user";
//    String xpath = " //servlet[servlet-name=//servlet-mapping[url-pattern='/user']/servlet-name/text()]/servlet-class";
//